package adrian.sunlight.ws.axis2;

import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

public class AuthenticationService {
	
	private Vector<String> AuthenticatedUsers 	= new Vector<String>();
	private Vector<Timer>  Sessions		   		= new Vector<Timer>();
	private String 		   error		   		= new String();
	
	private int defaultSessionTimeout			= 3600;
	
	private String[] Users 		= new String[]{"adrian", "popescu", "ionescu"};
	private String[] Passwords 	= new String[]{"123456", "123456", "123456"};
	
	public void setSessionTimeout(final String username, int seconds){
		int index = AuthenticatedUsers.indexOf(username);
		
		if(index >= 0){
			Timer t = Sessions.get(index);
			
			t.cancel();
			
			TimerTask task	= new TimerTask(){
				public void run(){
					logout(username);
				}
			};
			
			t.schedule(task, seconds * 1000);
			this.defaultSessionTimeout = seconds;
		}
	}
	
	private boolean validCombination(String username, String password){
		
		if((username == null) || (password == null)){
			return false;
		}
		
		if(this.Users.length > 0){
			for(int i=0; i<this.Users.length; i++){
				if(username.equals(this.Users[i]) && password.equals(this.Passwords[i])){
					return true;
				}
			}
		}
		
		return false;
	}
	
	public void login(final String username, String password){
		int index = AuthenticatedUsers.indexOf(username);
		
		if(index >= 0){
			;
		}
		else{//nu se poate loga de doua ori;
			if(this.validCombination(username, password)){
				AuthenticatedUsers.add(username);
				
				TimerTask task	= new TimerTask(){
					public void run(){
						try{
							logout(username);
						}
						catch(Exception e){
							error =  e.toString();
						}
					}
				};
				
				Timer t = new Timer();
				t.schedule(task, this.defaultSessionTimeout * 1000);
				
				Sessions.add(t);
			}
		}
	}
	
	public void logout(String username){
		
		int index = AuthenticatedUsers.indexOf(username);
		
		if(index >= 0){
			//------~ Anuleaza timer-ul ~------//
			Timer t = Sessions.get(index);
				  t.cancel();
				  t.purge();
			
			//------~ Sterge utilizatorul din lista ~------//
			AuthenticatedUsers.remove(username);
			Sessions.remove(index);
		}
	}
	
	public boolean isAuthenticated(final String username){
		int index = AuthenticatedUsers.indexOf(username);
		
		if(index >= 0){
			return true;
		}
		
		return false;
	}
	
	public String getError(){
		return error;
	}

}
